<style lang="less" scoped>
.RPI-contain {
  .rowNo {
    border-radius:0.2rem;
    background:#f0a800;
    color:#fff;
    padding:0 0.1rem;
    text-align: center;
    margin-right:0.1rem;
  }
  .detail-goods-list {
    padding:0;
    background: unset !important;
    .list-goods-warp {
      padding:0 0.2rem 0.2rem;
      &:active, &:focus {
        background: #ffffff;
      }
      .msg {
        padding-right: 0.3rem;
        p {
          word-break: break-all;
        }
      }
      .copy {
        color:#77babd;
        display: block;
        margin: auto 0;
        i {
          display: block;
          font-size:30px !important;
          &:first-of-type {
            padding-bottom: 0.3rem;
          }
          &:last-of-type {
            padding-top: 0.3rem;
            color:#f0a800 ;
          }
        }
      }
      .inputs-r {
        height:0.5rem;
        line-height: 0.5rem;
      }
      .inputs {
        height: 0.8rem;
        line-height: 0.8rem;
        input {
          margin-top:0.1rem;
          height:0.6rem;
          width:0.6rem;
          border:1px solid #ddd;
          border-radius: 0.1rem;
        }
        .invoiceNum {
          text-align: left;
          width:4.5rem;
        }
      }
    }
  }
}
.lineb {
  padding-bottom:0.25rem;
  border-bottom: 1px dashed #ccc;
  margin-bottom: 0.1rem;
}
.c-num-selector {
  height: 0.8rem;
  line-height: 0.8rem;
  background: #fff;
  z-index: 1;
  i {
    font-sizE:24px;
    color:#888;
    padding:0 0.2rem;
  }
  .c-num-inputs {
    margin-top:0.1rem;
    height:0.6rem;
    text-align: center;
    width:0.6rem;
    border:1px solid #ddd;
    border-radius: 0.1rem;
  }
}
</style>

<template>
  <div class="RPI-contain">
    <scroller lock-x scrollbar-y use-pullup :height="viewOnly?'-1':'-46'" :pullup-config="ScrollerConfig" ref="Scroller">
      <div class="detail-tab-lft">
        <div class="detail-goods-list">

          <div class="displayflex list-goods-warp" v-for="(item, index) in details" v-bind:id="`Inv${index}`" v-bind:class="viewOnly?'mb30':''">
            <div class="msg flex1" :style="{paddingRight:viewOnly?'0':''}">
              <p class="ft17"><em class="rowNo">{{index+1}}</em>{{item.GoodsName}}</p>
              <p>规格：{{item.GoodsSpec}}</p>
              <p>商品编码：{{item.GoodsCode}}</p>
              <p>单价：￥{{item.Price | fmoney}}</p>
              <p class="lineb">退货数：{{item.RpiQty}} {{item.Unit}}</p>
              <div class="cf" v-bind:class="viewOnly?'inputs-r':'inputs'">
                <label class="f-l">开票数：</label>
                <div class="c-num-selector displayflex f-l" v-if="viewOnly === false">
                  <i class="llse llse-cminus" @click="changeNum(item,-1)"></i>
                  <input class="flex1 c-num-inputs" number type="text" placeholder="0" v-model="item.Qty" @input="iptBlur(item)">
                  <i class="llse llse-cadd" @click="changeNum(item,1)"></i>
                  {{item.Unit}}
                </div>
                <div v-else>
                  {{item.Qty}} {{item.Unit}}
                </div>
              </div>
              <div v-bind:class="viewOnly?'inputs-r':'inputs'">发票号：<input class="invoiceNum" v-model="item.InvoiceNo" v-if="viewOnly === false"/><span v-else>{{item.InvoiceNo}}</span></div>
              <div v-bind:class="viewOnly?'inputs-r':'inputs'">金额：￥{{item.InvoiceAmount | fmoney}}</div>
            </div>
            <p>
              <div class="copy" v-if="item.BillState === 'R02'">
                <i class="llse llse-copy" v-on:click.stop="copy(item, index)"></i>
                <i class="llse llse-copydel" v-on:click.stop="delCopy(item, index)"></i>
              </div>
            </p>
          </div>

        </div>
      </div>
    </scroller>

    <div class="detail-bottom displayflex" v-if="viewOnly === false">
      <div class="flex1 btn-grp">
        <div class="btn" @click="save()">保存</div>
      </div>
    </div>

  </div>
</template>

<script>
export default {
  name:'refundOperate',
  data() {
    return {
      details: [],
      totalCountArray: [],
      viewOnly:true,
      ScrollerConfig:{
        content: '',
        downContent: '',
        height: 0,
        loadingContent: '',
        upContent: '',
      }
    };
  },
  computed: {
    userinfo() {
      return localStorage.getItem('userinfo') === null?null:JSON.parse(localStorage.getItem('userinfo'));
    },
    
  },
  watch: {
    details:{
      handler(n,o){
        this.details.forEach(x => {
          x.InvoiceAmount = x.Price * x.Qty;
        })
      },
      deep: true
    }
  },
  created() {
    if(this.$route.query.viewOnly === 'Y'){
      this.viewOnly = true;
    } else {
      this.viewOnly = false;
    }
    this.getData();
  },
  mounted() {
    this.$nextTick(function() {
      
    });
  },
  methods: {
    //获取详情
    getData() {
      var self = this;
      var query = {
        Guid: this.$route.query.Guid,
        BillNo: this.$route.query.BillNo,
        TenantGuid: this.userinfo.TenantGuid,
      };
      this.Ajax.post("GetInvoiceList", query).then((res) => {
        if (res.IsSuccess) {
          this.details = res.Datas;
        } else {
          this.Toast({
            message: res.ErrorMessage || '出现错误',
          });
        }
      }).catch((e) => {
        this.Toast({
          message: e.toString(),
        });
      });
    },
    copy(item, index){
      let arg = JSON.parse(JSON.stringify(item))
      arg.Qty = 0;
      arg.InvoiceNo = null;
      arg.InvoiceAmount = null;
      arg.IsCopyed = true;

      this.details.splice(index + 1,0,arg);

      this.$nextTick(()=>{
        let selector = this.$el.querySelector(`#Inv${index + 1}`),
            wrapper = document.getElementsByClassName('xs-container')[0],
            contain = document.getElementById('app'),
            ScrollH = 0 - selector.offsetTop,
            listH = document.getElementsByClassName('detail-tab-lft')[0].offsetHeight;
        if(listH < contain.offsetHeight) {
          ScrollH = 0;
        } else {
          if(this.details.length === index + 2){
            ScrollH =  (ScrollH + contain.offsetHeight) - selector.offsetHeight;
          }
        }
        wrapper.style.transition = `all 500ms`;
        wrapper.style.transform = `translateX(0px) translateY(${ScrollH}px) translateZ(0px) scale(1, 1)`;
      })
    },
    delCopy(item, index){
      if (item.IsCopyed) {
        this.details.splice(index,1);

        this.$nextTick(()=>{
          let selector = this.$el.querySelector(`#Inv${index - 1}`),
              wrapper = document.getElementsByClassName('xs-container')[0],
              contain = document.getElementById('app'),
              ScrollH = 0 - selector.offsetTop,
              listH = document.getElementsByClassName('detail-tab-lft')[0].offsetHeight;
          
          if(listH - (0 - ScrollH) < contain.offsetHeight)
          {
            ScrollH = 0 - listH + contain.offsetHeight;
          }
          if(ScrollH > 0){
            ScrollH = 0;
          }
          wrapper.style.transition = `all 500ms`;
          wrapper.style.transform = `translateX(0px) translateY(${ScrollH}px) translateZ(0px) scale(1, 1)`;
        })
        
      } else {
        this.Toast({ message:'请不要删除源数据' });
      }
    },

    CheckDatas() {
      for(let i = 0; i < this.details.length; i++){
        let x = this.details[i];
        if (parseInt(x.Qty) <= 0) {
          this.Toast(`第${i + 1}条的退货开票数不能为零`);
          return false;
        }
        if (!x.InvoiceNo) {
          this.Toast(`第${i + 1}条的退货发票号为空`);
          return false;
        }
      }

      let sourceData = this.details.filter(x => {
        return x.IsCopyed === false;
      });
      sourceData.forEach(x => {
        x.TotalQty = this.countAll(x);
      });

      for (const i in sourceData) {
        let x = sourceData[i];

        if (parseInt(x.RpiQty) > x.TotalQty) {
          this.Toast(`商品【${x.GoodsName}】的退货开票数量不足`);
          return false;
        }
        if (parseInt(x.RpiQty) < x.TotalQty) {
          this.Toast(`商品【${x.GoodsName}】的退货开票数量超过退货数量`);
          return false;
        }
      }
      return true;
    },

    save(){
      if(this.CheckDatas() == true){
        let query = {
          MVList: this.details,
          SettleBillNo: this.$route.query.SettleBillNo,
          TenantGuid: this.userinfo.TenantGuid,
          MedGuid: this.$route.query.MedGuid,
          UpdateUserID: this.userinfo.StaffID,
          UpdateUserName: this.userinfo.Name,
        };
        this.Ajax.post("SaveInvoiceEntries", query).then((res) => {
          if (res.IsSuccess) {
            this.Toast('发票录入完成');
            this.$router.replace({
              path: '/order/refundOperate',
              query: {
                Guid: this.$route.query.Guid,
              }
            })
          } else {
            this.Toast({
              message: res.ErrorMessage || '出现错误',
            });
          }
        }).catch((e) => {
          this.Toast({
            message: e.toString(),
          });
        });
      }
    },

    //加减
    changeNum: function(item, way) {
      if (way > 0) {
        item.Qty++;
        if (this.countAll(item) > parseInt(item.RpiQty)) {
          this.Toast({ message:'开票数不能大于退货数'});
          item.Qty--;
        }
      } else if (way < 0 && item.Qty > 0) {
        item.Qty--;
      } else {
        this.Toast({
          message: "请输入大于0的数"
        });
      }
    },

    //数量输入框
    iptBlur(item) {
      if (item.Qty && !isNaN(item.Qty)) {
        if (this.countAll(item) > parseInt(item.RpiQty)) {
          this.Toast({ message:'开票数不能大于退货数'});
          item.Qty = 0;
          return;
        } else {
          item.Qty = item.Qty*1;
        }
      } else {
        item.Qty = 0;
      }
    },

    //统计数量
    countAll(item) {
      let total = 0;
      this.details.forEach(x => {
        if(item.GoodsGuid === x.GoodsGuid){
          total += parseInt(x.Qty || '0');
        };
      });
      return total;
    }
  },
}
</script>
